new Vue({
    el: '#app',
    mixins: [Query],//组件配置文件，路径/utils/components.js
    data() {
        return {
            form: {//查询筛选
                value: '',
                value2: '-', // 状态：'-'全部、'0'待审核、'2'已通过、'3'拒绝
                PageNumber: 1, //页码
                RowAmount: 20,
                // Condition 两参：关键词,状态
                Condition: utf8ToBase64(`%%,%%`),
            },
            confirmContractDialogVisible: false,
            confirmContractRow: null,
            dialogInvoiceViewVisible: false,
            invoiceViewList: [],
        }
    },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.getColumn(); //查询表头数据
         * 2.this.getList(this.form); //查询表格数据
         * 3.this.getTreeData();//查询树
         */
    },
    methods: {
        handleSerach() { //筛选
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
        // 状态切换：更新 Condition 第二参数并刷新列表
        handleTabsClick() {
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
        // acceptOrder(row) {
        //     try {
        //         const { tableName, primaryKey } = $('#table').data('options');
        //         const id = row[primaryKey];
        //         if (!id) { this.$message.error('未获取到订单编号'); return; }
        //         generalApi.generalQueryByTableNameWithOriginal({ Data: tableName, Condition: `${primaryKey}='${id}'` }).then(async data => {
        //             if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return; }
        //             data[0].Row_Status = '2';

        //             const orderAmount = Number((data[0] && data[0].Amount) || row.Amount || 0);
        //             const unitPriceId = row.Acquisition_Unit_Price_SerialNumber || data[0].Acquisition_Unit_Price_SerialNumber || '';

        //             // 若尚未存在阶段付款明细，则按报价阶段生成到 acquisition_order_paystages
        //             let paystagesToAdd = [];
        //             try {
        //                 const existed = await generalApi.generalQueryByTableNameWithOriginal({
        //                     Data: 'acquisition_order_paystages',
        //                     Condition: `Acquisition_Order_SerialNumber='${id}'`
        //                 });
        //                 const hasExisting = Array.isArray(existed) && existed.length > 0;
        //                 if (!hasExisting && unitPriceId) {
        //                     const stagedRes = await generalApi.generalQueryByTableNameWithOriginal({
        //                         Data: 'acquisition_unitprice_staged_payment',
        //                         Condition: `Acquisition_Unit_Price_SerialNumber='${unitPriceId}'`
        //                     });
        //                     const stagedArr = Array.isArray(stagedRes) ? stagedRes : (stagedRes && stagedRes.Data) || [];
        //                     paystagesToAdd = (stagedArr || []).map(sp => {
        //                         const percentVal = Number(sp.Percent || 0);
        //                         const due = Number.isFinite(orderAmount * percentVal / 100)
        //                             ? Number((orderAmount * percentVal / 100).toFixed(2))
        //                             : '';
        //                         return {
        //                             Acquisition_Order_Paystages_SerialNumber: '',
        //                             Acquisition_Order_SerialNumber: id,
        //                             Stage_Name: sp.Stage_Name || '',
        //                             Percent: sp.Percent !== undefined ? sp.Percent : '',
        //                             Due_Amount: due !== '' ? String(due) : '',
        //                             Trading_Amount: due !== '' ? String(due) : '',
        //                             Paid_Amount: '0',
        //                             Collection_Date: '',
        //                             Row_Status: '0'
        //                         };
        //                     });
        //                 }
        //             } catch (e) { /* 初始化失败不阻塞接受逻辑 */ }

        //             const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
        //             const lJSONObject_DataSet = { Modify: lJSONObject_Modify, Add: {} };
        //             if (paystagesToAdd.length > 0) lJSONObject_DataSet.Add['acquisition_order_paystages'] = paystagesToAdd;
        //             const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        //             lJSONObject_DataSet['Add']['base_operation_log'] = [{
        //                 Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '接受采购订单',
        //                 Operation_Main, Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
        //             }];
        //             return generalApi.generalSaveByRequestBody({ Data: lJSONObject_DataSet });
        //         }).then(res => {
        //             if (res && (res.Status === 'success')) { this.$message.success('已通过'); this.$set(row, 'Row_Status', '2'); this.getList(this.form); }
        //             else if (res) { this.$message.error(res.Message || '保存失败'); }
        //         }).catch(() => this.$message.error('系统错误，请联系开发者!'));
        //     } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        // },
        // // 拒绝：将当前行状态置为3，并记录拒绝原因
        // rejectOrder(row) {
        //     this.$prompt('请输入拒绝原因', '拒绝订单', { confirmButtonText: '确定', cancelButtonText: '取消', inputPattern: /.+/, inputErrorMessage: '拒绝原因不能为空' })
        //         .then(({ value }) => {
        //             const reason = value || '';
        //             try {
        //                 const { tableName, primaryKey } = $('#table').data('options');
        //                 const id = row[primaryKey];
        //                 generalApi.generalQueryByTableNameWithOriginal({ Data: tableName, Condition: `${primaryKey}='${id}'` })
        //                     .then(data => {
        //                         if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return; }
        //                         data[0].Row_Status = '3';
        //                         const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
        //                         const lJSONObject_DataSet = {
        //                             Modify: lJSONObject_Modify,
        //                             Add: {
        //                                 // 与求购大厅保持一致，记录到 acquisition_order_examine_log
        //                                 acquisition_order_examine_log: [{
        //                                     Acquisition_Order_SerialNumber: id,
        //                                     Reason: reason,
        //                                     Operation_ID: getCookie('user') || ''
        //                                 }],
        //                                 base_operation_log: [{
        //                                     Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '拒绝采购订单',
        //                                     Operation_Main: JSON.stringify(deepClone(lJSONObject_Modify)),
        //                                     Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
        //                                 }]
        //                             }
        //                         };
        //                         return generalApi.generalSaveByRequestBody({ Data: lJSONObject_DataSet });
        //                     }).then(res => {
        //                         if (res && (res.Status === 'success')) { this.$message.success('已拒绝'); this.$set(row, 'Row_Status', '3'); this.getList(this.form); }
        //                         else if (res) { this.$message.error(res.Message || '保存失败'); }
        //                     }).catch(() => this.$message.error('系统错误，请联系开发者!'));
        //             } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        //         }).catch(() => {});
        // },
        // 已通过后：确认合同（买方视角），跳转到买方合同详情页
        confirmContract(row) {
            try {
                const orderSerial = row.Acquisition_Order_SerialNumber || '';
                if (!orderSerial) {
                    this.$message.error('未找到订单编号，无法跳转合同详情');
                    return;
                }
                const url = `./buyer_contract_details.html?orderSerial=${encodeURIComponent(orderSerial)}`;
                window.location.href = url;
            } catch (e) {
                console.error(e);
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        // 线上签约入口
        startOnlineSigning(row) {
            try {
                this.confirmContractDialogVisible = false;
                this.$message.success('已选择：线上签约');
                // TODO: 在此发起线上签约流程或跳转到签约页面
            } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        },
        // 线下签约入口
        startOfflineSigning(row) {
            try {
                this.confirmContractDialogVisible = false;
                this.$message.success('已选择：线下签约');
                // TODO: 在此记录线下签约意向或跳转到线下流程页面
            } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        },
        async openInvoiceViewer(row) {
            try {
                const orderSerial = row.Acquisition_Order_SerialNumber || '';
                if (!orderSerial) {
                    this.$message.error('未找到订单编号');
                    return;
                }
                const res = await generalApi.generalQueryByTableName({ Data: 'acquisition_order_invoice', Condition: `Acquisition_Order_SerialNumber='${orderSerial.replace(/'/g, "''")}'` });
                const arr = Array.isArray(res) ? res : (res.Data || []);
                this.invoiceViewList = (arr || []).map(i => ({ url: (imageApi || '') + String(i.Picture_URL || '') })).filter(j => j.url);
                this.dialogInvoiceViewVisible = true;
            } catch (e) {
                console.error(e);
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        handleShow(row) { // 查询详情：跳转到采购订单详情页
            try {
                const { primaryKey } = $('#table').data('options');
                const applyId = row.Acquisition_Order_SerialNumber || row[primaryKey] || '';
                if (!applyId) {
                    this.$message.error('未找到订单编号，无法跳转详情');
                    return;
                }
                const url = `../acquisition_order/details.html?applyId=${encodeURIComponent(applyId)}&fromPage=purchase_order`;
                window.location.href = url;
            } catch (error) {
                console.error(error);
                this.$message({ message: '系统错误，请联系开发者!', type: 'error' });
            }
        }
        
    }
})
